<template>
  <div class="login">
    <van-nav-bar title="登录" />
    <van-form @submit="onSubmit">
      <van-field
        required
        v-model="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        required
        v-model="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      >
        <template #button>
          <van-button size="small" type="primary">发送验证码</van-button>
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button
          :disabled="isLoading"
          :loading="isLoading"
          loading-text="加载中..."
          round
          block
          type="info"
          native-type="submit"
        >
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { reqUserLogin } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  data() {
    return {
      mobile: '13911111111',
      code: '246810',
      rules: {
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'onBlur' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式错误',
            trigger: 'onBlur'
          }
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'onBlur' },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误',
            trigger: 'onBlur'
          }
        ]
      },
      isLoading: false
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    async onSubmit() {
      this.isLoading = true
      try {
        const res = await reqUserLogin(this.mobile, this.code)
        console.log(res)
        // console.log('登录成功')
        this.$toast.success('登录成功')
        this.setToken(res.data.data)
        if (this.$route.query.goBack) {
          // 回退
          this.$router.back()
        } else {
          const back = this.$route.query.back || '/'
          this.$router.push(back)
        }

        // if (this.$route.query.back) {
        //   this.$router.push(this.$route.query.back)
        // } else {
        //   this.$router.push('/')
        // }
      } catch (err) {
        console.log('登录失败', err)
        this.$toast.fail('登录失败')
      }
      this.isLoading = false
    }
  }
}
</script>

<style></style>
